package org.leiyang.common.dtos;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.leiyang.common.entities.MsgOneToOne;
import org.leiyang.common.entities.User;
import org.leiyang.common.util.TimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.Map;

import static org.leiyang.common.util.Constants.TIME_FORMATTER;

/**
 * 用于显示到APP聊天页的消息
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class MsgDTO implements Serializable, Comparable<MsgDTO> {
    private static final Logger logger = LoggerFactory.getLogger(MsgDTO.class);

    private static final long serialVersionUID = 1L;

    /**
     * 主要分为system——系统消息；user——用户消息
     */
    private String type;

    /**
     * 消息详情
     */
    private MsgDetailDTO msg;

    /**
     * 将{@link MsgOneToOne} 转化为 {@link MsgDTO}
     */
    public static MsgDTO convertFromMsgOneToOne(MsgOneToOne msgOneToOne, Map<Long, User> usersMap) {
//        logger.info("usersMap: {}", usersMap);
//        logger.info("msgOneToOne.getFromUserId: {}", msgOneToOne.getFromUserId());
        User fromUser = usersMap.get(msgOneToOne.getFromUserId());
        return convertFromMsgOneToOneV1(msgOneToOne, fromUser);
    }

    public static MsgDTO convertFromMsgOneToOneV1(MsgOneToOne msgOneToOne, User fromUser) {
        UserInfoDTO userinfo = UserInfoDTO.builder().uid(fromUser.getId()).username(fromUser.getUsername()).face(fromUser.getAvater()).build();
        ContentDTO contentDTO = new ContentDTO();
        String msgText = "text";
        if(msgOneToOne.getMsgType() == 2) {
            contentDTO.setText(msgOneToOne.getTextMsg());
        } else if (msgOneToOne.getMsgType() == 3) {
            contentDTO.setUrl(msgOneToOne.getAvMsgUrl());
            contentDTO.setLength("00:06");
            msgText = "voice";
        } else if (msgOneToOne.getMsgType() == 5) {
            contentDTO.setUrl(msgOneToOne.getAvMsgUrl());
            msgText = "img";
            contentDTO.setW(msgOneToOne.getImgWidth());
            contentDTO.setH(msgOneToOne.getImgHeight());
        }
        MsgDetailDTO msg = MsgDetailDTO.builder().id(msgOneToOne.getId()).type(msgText)
                .time(TimeUtils.formatMills(msgOneToOne.getTime(), TIME_FORMATTER))
                .content(contentDTO).userinfo(userinfo).build();
        return MsgDTO.builder().type("user").msg(msg).build();
    }

    @Override
    public int compareTo(MsgDTO o) {
        return (int) (this.msg.getId() - o.getMsg().getId());
    }
}
